<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .imgBox {
      width: 500px;
      height: 300px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }

    img {
      width: 500px;
      height: 300px;
      position: absolute;
      opacity: 0;
      z-index: 0;
      transition: 0.3s;
    }

    .btnBox {
      position: fixed;
      bottom: 10px;
      width: auto;
      left: 50%;
      transform: translateX(-50%);
    }

    img.active {
      opacity: 1;
      z-index: 2;
    }
  </style>
</head>

<body>
  <div class="imgBox">
    <img src="./img/1.jpg" alt="">
    <img src="./img/2.jpg" alt="">
    <img src="./img/3.jpg" alt="">
  </div>
  <div class="btnBox">
    <button>上一张</button>
    <button>下一张</button>
  </div>
</body>
<script>
  // 通过标签名获取两个按钮
  var btn = document.getElementsByTagName('button')
  // 通过标签名获取三张图片
  var img = document.getElementsByTagName('img')
  // 要显示的图片的下标
  var index = 0

  // 根据index的值决定哪一张图片显示
  function show() {
    // 清空class
    for (var i = 0; i < 3; i++) {
      img[i].className = ''
    }
    // 修改index下标的图片的class为active
    img[index].className = 'active'
  }

  show()

  // 显示下一张图片
  function next() {
    if (index == 2) {
      index = 0
    } else {
      index++
    }
    show()
  }

  // 显示上一张图片
  function last() {
    if (index == 0) {
      index = 2
    } else {
      index--
    }
    show()
  }

  // 给按钮绑定点击事件
  btn[1].onclick = next // 下一张按钮
  btn[0].onclick = last // 上一张按钮
</script>

</html>